package com.padakeji.android.pworks.module.image.model;

import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import com.padakeji.android.pworks.module.image.entity.ImageDirectory;
import com.padakeji.android.pworks.module.image.entity.ImageInfo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import static android.provider.BaseColumns._ID;
import static android.provider.MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME;
import static android.provider.MediaStore.Images.ImageColumns.BUCKET_ID;
import static android.provider.MediaStore.MediaColumns.DATA;
import static android.provider.MediaStore.MediaColumns.DATE_ADDED;

/**
 * Created by AtanL on 2015/9/15.
 */
public class ImageModel {

    public interface OnImageLoadListener {
        void onImagesLoad(List<ImageDirectory> imageDirectories);
    }

    private AppCompatActivity mContext;
    private OnImageLoadListener onImageLoadListener;


    public ImageModel(AppCompatActivity context) {
        if (context == null) {
            throw new RuntimeException("A context must be passed as a parameter to constructor.");
        }

        this.mContext = context;
    }


    public void setOnImageLoadListener(OnImageLoadListener onImageLoadListener) {
        this.onImageLoadListener = onImageLoadListener;
    }

    public void loadImages() {
        AsyncTask<Void, Void, List<ImageDirectory>> task = new AsyncTask<Void, Void, List<ImageDirectory>>() {
            @Override
            protected List<ImageDirectory> doInBackground(Void... params) {
                Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                String selection = MediaStore.Images.Media.MIME_TYPE + " = ? or " + MediaStore.Images.Media.MIME_TYPE + " = ?";
                String[] selectionArgs = new String[]{"image/jpeg", "image/png"};
                String sortOrder = MediaStore.Images.Media.DATE_MODIFIED + " desc";
                Cursor data = mContext.getContentResolver().query(uri, null, selection, selectionArgs, sortOrder);

                if (data == null) {
                    return null;
                }

                // Key is directory id.
                LinkedHashMap<String, ImageDirectory> imageDirectoryMap = new LinkedHashMap<>();
                ImageDirectory directoryKeptAll = new ImageDirectory();
                directoryKeptAll.id = "all";
                directoryKeptAll.name = "所有图片";
                imageDirectoryMap.put(directoryKeptAll.id, directoryKeptAll);

                while (data.moveToNext()) {

                    int imageId = data.getInt(data.getColumnIndexOrThrow(_ID));
                    String bucketId = data.getString(data.getColumnIndexOrThrow(BUCKET_ID));
                    String bucketDisplayName = data.getString(data.getColumnIndexOrThrow(BUCKET_DISPLAY_NAME));
                    String path = data.getString(data.getColumnIndexOrThrow(DATA));

                    ImageInfo imageInfo = new ImageInfo();
                    imageInfo.id = imageId;
                    imageInfo.path = path;

                    directoryKeptAll.images.add(imageInfo);

                    ImageDirectory tmpDir = imageDirectoryMap.get(bucketId);
                    if (tmpDir == null) {
                        tmpDir = new ImageDirectory();
                        tmpDir.id = bucketId;
                        tmpDir.name = bucketDisplayName;
                        tmpDir.coverImagePath = path;
                        long dateAdded = data.getLong(data.getColumnIndexOrThrow(DATE_ADDED));
                        tmpDir.dateAdded = dateAdded;
                        imageDirectoryMap.put(tmpDir.id, tmpDir);
                    }
                    tmpDir.images.add(imageInfo);
                }

                List<ImageDirectory> directories = null;
                if (imageDirectoryMap.size() != 0) {
                    directories = new ArrayList<>();
                    for (String key : imageDirectoryMap.keySet()) {
                        ImageDirectory d = imageDirectoryMap.get(key);
                        directories.add(d);
                    }
                }

                return directories;
            }

            @Override
            protected void onPostExecute(List<ImageDirectory> imageDirectories) {
                super.onPostExecute(imageDirectories);
                if (onImageLoadListener != null && imageDirectories != null) {
                    onImageLoadListener.onImagesLoad(imageDirectories);
                }
            }
        };
        task.executeOnExecutor(Executors.newFixedThreadPool(1));
    }


}
